import * as React from 'react';
import { escape } from '@microsoft/sp-lodash-subset';
import Api from '../../config/api';
import { Link } from '@microsoft/office-ui-fabric-react-bundle';
import css from './Home.module.scss';
import { DetailsList, DetailsListLayoutMode, IColumn,SelectionMode } from 'office-ui-fabric-react/lib/DetailsList';
import { mergeStyleSets } from 'office-ui-fabric-react/lib/Styling';
import { MarqueeSelection } from 'office-ui-fabric-react/lib/MarqueeSelection';
import {
  TooltipHost, DatePicker, DayOfWeek,
  Dropdown,
  IDropdownOption,
  IIconProps
} from 'office-ui-fabric-react';
import { Toggle } from 'office-ui-fabric-react/lib/Toggle';
import { Announced } from 'office-ui-fabric-react/lib/Announced';
import { TextField, MaskedTextField } from 'office-ui-fabric-react/lib/TextField';
import { DefaultButton, PrimaryButton,IconButton } from 'office-ui-fabric-react/lib/Button';
import { FontIcon } from 'office-ui-fabric-react/lib/Icon';
// import {DocumentsListGUID,PDFDocumentsListGUID} from '../../config/ListGuid';
import { SearchBox } from 'office-ui-fabric-react/lib/SearchBox';

export interface ISearchDocument {
    itemid: string;
    title: string;
    docnumber: string;
    link: string;
    itemguid: string;
    createdtime:Date;
  }

const classNames = mergeStyleSets({
  fileIconHeaderIcon: {
    padding: 0,
    fontSize: '16px',
  },
  fileIconCell: {
    textAlign: 'center',
    selectors: {
      '&:before': {
        content: '.',
        display: 'inline-block',
        verticalAlign: 'middle',
        height: '100%',
        width: '0px',
        visibility: 'hidden',
      },
    },
  },
  fileIconImg: {
    verticalAlign: 'middle',
    maxHeight: '16px',
    maxWidth: '16px',
  },
  controlWrapper: {
    display: 'flex',
    flexWrap: 'wrap',
  },
  exampleToggle: {
    display: 'inline-block',
    marginBottom: '10px',
    marginRight: '30px',
  },
  selectionDetails: {
    marginBottom: '20px',
  },

  searchdiv:{
      
  }
});
const controlStyles = {
  root: {
    margin: '0 30px 20px 0',
    maxWidth: '300px',
  },
};

const SearchFriendIcon: IIconProps = { iconName: 'Search' };

const emojiIcon: IIconProps = { iconName: 'Cancel' };
const SearchiIcon: IIconProps = { iconName: 'Search' };

export interface IDetailsListDocumentsExampleState {
    searchtext: string;
    columns: IColumn[];
    searchlist: ISearchDocument[];
}


var searchval=null;

var isprev:boolean=false;
var isnext:boolean=false;

const onFormatDate0 = (date?: Date): string => {
    return !date ? '' : (date.getFullYear())+ '-' + ((date.getMonth() + 1)>=10?(date.getMonth() + 1):''+(date.getMonth() + 1))+'-'+(date.getDate()>=10?date.getDate():'0'+date.getDate());
  };
  
  const onFormatDate = (date?: Date): string => {
    var timestamp: number = date.getTime();
    timestamp = timestamp / 1000;
    // 增加8个小时，北京时间比utc时间多八个时区
    timestamp = timestamp + 8 * 60 * 60;
    var newdate = new Date(timestamp * 1000);
    return !newdate ? '' : (newdate.getFullYear()) + '-' + ((newdate.getMonth() + 1) >= 10 ? (newdate.getMonth() + 1) : '' + (newdate.getMonth() + 1)) + '-' + (newdate.getDate() >= 10 ? newdate.getDate() : '0' + newdate.getDate()) + " " + (newdate.getHours() >= 10 ? newdate.getHours() : '0' + newdate.getHours()) + ":" + (newdate.getMinutes() >= 10 ? newdate.getMinutes() : '0' + newdate.getMinutes());
  };

export default class Search extends React.Component<any, IDetailsListDocumentsExampleState> {

  constructor(props: any) {
    super(props);

    const columns: IColumn[] = [
        {
            key: 'column1',
            name: 'File Type',
            className: classNames.fileIconCell,
            iconClassName: classNames.fileIconHeaderIcon,
            ariaLabel: 'Column operations for File type, Press to sort on File type',
            iconName: 'Page',
            isIconOnly: true,
            fieldName: 'name',
            minWidth: 16,
            maxWidth: 16,
            onRender: (item: ISearchDocument) => (
              <TooltipHost content={item.title}  onClick={()=>this.goapply(item)}>
                <img src="https://static2.sharepointonline.com/files/fabric/assets/item-types/16/pdf.svg" className={classNames.fileIconImg} alt={`file icon`} />
              </TooltipHost>
            ),
          },
        {
          key: 'title',
          name: '文件名',
          fieldName: 'title',
          minWidth: 150,
          maxWidth: 200,
          isRowHeader: true,
          isResizable: true,
          isCollapsible: true,
          data: 'string',
          onRender: (item: ISearchDocument) => {
            return <div className="qxxz" onClick={()=>this.goapply(item)} >{item.title}</div>;
          },
          isPadded: true,
        },
        {
          key: 'docnumber',
          name: '文档编号',
          fieldName: 'docnumber',
          minWidth: 100,
          maxWidth: 150,
          isResizable: true,
          data: 'string',
          onRender: (item: ISearchDocument) => {
            return <div className="qxxz" onClick={()=>this.goapply(item)} >{item.docnumber}</div>;
          },
          isPadded: true,
        },
        {
          key: 'createdtime',
          name: '创建时间',
          fieldName: 'Created',
          minWidth: 70,
          maxWidth: 90,
          isResizable: true,
          isCollapsible: true,
          data: 'string',
          onRender: (item: ISearchDocument) => {
            return <div className="qxxz" onClick={()=>this.goapply(item)} >{onFormatDate(new Date(item.createdtime.toString().replace('/T/g',' ').split('Z')[0]))}</div>;
          },
        },
      ];
    this.state = {
        searchtext:"",
        columns:columns,
        searchlist:[]
    };
    
  }

  //动态更新绑定数据
  public async componentDidMount() {
    // 
    var searchtext = this.props.match.params.searchtext;

    this.setState({
        searchtext: searchtext
    });
    this.getloadlist(searchtext);
  }


  private searchbtn = async () => {
    
  }

  private clearsearch=async ()=>{
    await this.componentDidMount();
  }

  private goapply=(item?:ISearchDocument, index?: number, ev?: React.FocusEvent<HTMLElement>)=>{
    //   top.location.href=item.link;
      if(item.link!=null&&item.link!=""){
        var a = document.createElement('a');
        a.style.display = 'none';
        a.href = item.link;
        a.target="_blank";
        document.body.appendChild(a);
        a.click();  // 自动触发点击a标签的click事件
        document.body.removeChild(a);
      }
  }

  private Searchbtn=(e)=>{
    //
    this.getloadlist(e);
  }
  

  public render() {
    const { columns, searchlist,searchtext } = this.state;
    return (
        <div className={css.layout_body_home}>
            <a href='#/home'>{'< 返回'}</a>
            <div className={css.h_center_div}>
                <div className={css.h_search_div}>
                    <div className={css.h_search}>
                        <SearchBox
                            className={css.h_search_input}
                            placeholder="Search"
                            value={searchtext}
                            onClear={ev => {
                                this._onFilterSearch(ev,null)
                            }}
                            onChange={(_, newValue) => {this._onFilterSearch(_,newValue)}}
                            onSearch={newValue => this.Searchbtn(newValue)}
                        />
                    </div>
                    <div className={css.h_search_btn}><PrimaryButton className={css.h_search_btn_p} iconProps={SearchFriendIcon} text="搜索" onClick={() => this.Searchbtn(searchtext)} allowDisabledFocus /></div>
                </div>
            </div>
            <div className={css.searchdiv}>
                <div className={css.search_list}>
                    <DetailsList
                        items={searchlist}
                        columns={columns}
                        selectionMode={SelectionMode.none}
                        //getKey={this._getKey}
                        setKey="multiple"
                        layoutMode={DetailsListLayoutMode.justified}
                        isHeaderVisible={true}
                        //selection={this._selection}
                        //selectionPreservedOnEmptyClick={true}
                        //onItemInvoked={this._onItemInvoked}
                        enableUpdateAnimations={true}
                        enterModalSelectionOnTouch={false}
                        ariaLabelForSelectionColumn="Toggle selection"
                        ariaLabelForSelectAllCheckbox="Toggle selection for all items"
                        checkButtonAriaLabel="select row"
                    />
                </div>

            </div>

        </div>
    );
  }

  private _onFilterSearch = (ev: React.FormEvent<HTMLInputElement | HTMLTextAreaElement>,text: string): void => {
    this.setState({
        searchtext:text
    });
  }

  public async getloadlist(searchtest) {
    var u = await Api._getcurrentUser();
    if (u != null) {
      const items: ISearchDocument[] = [];
      var so1:IDropdownOption[]=[];
      // var params = {
      //   guid: PDFDocumentsListGUID,//ListGuid
      //   Asc: false,
      //   Filter: "substringof('" + searchtest + "',Title) or substringof('" + searchtest + "',OData__x6587__x6863__x7f16__x53f7_) or substringof('" + searchtest + "',OData__x521b__x5efa__x90e8__x95e8_) or substringof('" + searchtest + "',OData__x521b__x5efa__x79d1__x5ba4_) or substringof('" + searchtest + "',OData__x6587__x6863__x7c7b__x578b_)"
      // };
    //   var paramsf = {
    //     folders: "DocLib",
    //   };
    //   var params = {
    //     guid: DocumentsListGUID,//ListGuid
    //   };
     // var datalist = await Api._getSearchData(params);
    //   var datalist1 = await Api._getSearchFolderData(paramsf);
    //   
    //   
      // if (datalist && datalist.length > 0) {
      //   for (let i = 0; i < datalist.length; i++) {
      //     items.push({
      //       itemid:datalist[i].Id,
      //       title: datalist[i].Title,
      //       docnumber:datalist[i].OData__x6587__x6863__x7f16__x53f7_,
      //       link:datalist[i].ServerRedirectedEmbedUri,
      //       itemguid:datalist[i].GUID,
      //       createdtime:datalist[i].Modified
      //     });
      //   }
      // }
      this.setState({
        searchlist:items
      });
    }else{
        this.setState({
            searchlist:[]
          });
    }
    
  }

  
}
